package com.wswy.wzcx.ui.car.choose

import android.arch.lifecycle.Observer
import android.graphics.Color
import android.os.Bundle
import android.support.v4.widget.DrawerLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration
import com.wswy.wzcx.R
import com.wswy.wzcx.model.car.CarTypeInfo
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.widget.SideBar
import kotlinx.android.synthetic.main.fragment_choose_car_brand.*

class ChooseBrandFragment : CBaseFragment() {

    companion object {
        private const val TAG = "ChooseBrandFragment"
    }

    private lateinit var chooseCarViewModel:ChooseCarViewModel

    private lateinit var seriesAdapter: BrandsAdapter
    private lateinit var seriesDecoration : StickyRecyclerHeadersDecoration

    private val indexed = IntArray(26) {-1}


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_choose_car_brand,container,false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        chooseCarViewModel = provideViewModelFromActivity(ChooseCarViewModel::class.java)

        drawerLayout.setScrimColor(Color.TRANSPARENT)
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)

        val adapter = BrandsAdapter().apply {

            setOnItemClickListener { _, _, t ->

                //展开
                drawerLayout.openDrawer(fl_right_container)

                chooseCarViewModel.chooseCar.brand = t

                t?.id?.let {
                    openSeries(it)
                }

            }

        }

        val layoutManager = LinearLayoutManager(context)

        recycler_view.layoutManager = layoutManager
        recycler_view.addItemDecoration(StickyRecyclerHeadersDecoration(adapter))
        recycler_view.adapter = adapter




        seriesAdapter = BrandsAdapter(false).apply {

            setOnItemClickListener { _, _, t ->

                //收起
                drawerLayout.closeDrawer(fl_right_container)

                chooseCarViewModel.chooseCar.series = t

                t?.id?.let {
                   // openModel(it)
                    chooseCarViewModel.setSeries(it)
                }
            }

            registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver(){
                override fun onChanged() {
                    super.onChanged()
                    seriesDecoration.invalidateHeaders()
                }
            })

        }


        seriesDecoration = StickyRecyclerHeadersDecoration(seriesAdapter)
        recycler_view_series.layoutManager = LinearLayoutManager(context)
        recycler_view_series.addItemDecoration(seriesDecoration)
        recycler_view_series.adapter = seriesAdapter

        chooseCarViewModel.getBrandsLiveData().observe(this, Observer {

            it?.run {

                if (isOk()){
                    var len = 0

                    data?.fold(arrayListOf<CarTypeInfo>()) { list, item ->
                        indexed[item.title?.get(0)?.minus('A')?:0] = len

                        item.list?.let {
                            list.addAll(it)
                            len += it.size
                        }
                        list
                    }?.run {
                        adapter.setNewData(this)
                        adapter.notifyDataSetChanged()
                    }

                }
            }

        })

        chooseCarViewModel.getSeriesLiveData().observe(this, Observer {
            it?.run {

                if (isOk()) {


                    data?.fold(arrayListOf<CarTypeInfo>()) { list, item ->
                        item.list?.let {
                            list.addAll(it)
                        }
                        list
                    }?.run {
                        seriesAdapter.setNewData(this)
                        seriesAdapter.notifyDataSetChanged()
                        if(isNotEmpty()){
                            recycler_view_series.scrollToPosition(0)
                        }
                    }

                }else{
                    seriesAdapter.clearData()
                    seriesAdapter.notifyDataSetChanged()
                }

            }
        })


        indexBar.setOnChooseLetterChangedListener(object :SideBar.OnChooseLetterChangedListener{
            override fun onChooseLetter(s: String?) {

                s?.get(0)?.run {

                    if (Character.isLetter(this)){

                        val pos = indexed[this - 'A']
                        if (pos >= 0) {
                            layoutManager.scrollToPositionWithOffset(pos, 0)
                        }

                    }else if (this == '#'){
                        layoutManager.scrollToPositionWithOffset(0, 0)
                    }

                }



            }

            override fun onNoChooseLetter() {
            }

        })


        chooseCarViewModel.loadBrands()


    }

    private fun openSeries(brandId:String){

        chooseCarViewModel.getSeries(brandId)


    }



    override fun onBackPress(): Boolean {
        if (drawerLayout.isDrawerOpen(fl_right_container)){
            drawerLayout.closeDrawer(fl_right_container)

            return true
        }
        return super.onBackPress()
    }
}